<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 4月9日
 * Time: 13:58
 * 这个不同于dofun，这个将所有操作全都独立出来。后续对接新offer，建议以此为模板。
 */
namespace app\api\controller;


use app\api\controller\Offer;
use app\api\model\MobuppsData;

class Mobupps
{
    private $app_id = 'wmadv';
    private $app_key = '11267952b6adb419b32d8d3d823bd59defcc80b8e0cf22094d65ddba6ae14f5c';

    public function index()
    {
        $limit = 100;//获取条数
        $filters = '&fields[]=payout_type&fields[]=conversion_cap&fields[]=preview_url&fields[]=payout_cap&fields[]=name&fields[]=id&fields[]=description&fields[]=default_payout&filters[payout_type]=cpa_flat';
        $url = 'https://api.hasoffers.com/Apiv3/json?NetworkId=wmadv&Target=Affiliate_Offer&Method=findMyApprovedOffers&api_key='.$this->app_key.'&limit='.$limit.'&contain[]=TrackingLink&contain[]=Country'.$filters;

        //echo $url;exit;
        $str = json_decode(file_get_contents($url),true);
        $data = $str['response']['data']['data'];
        dump($data);
    }

    /*
     * 获取offer数据
     */
    public function getData()
    {
        $data_mod = new MobuppsData;

        $limit = 100;//获取条数
        $filters = '&fields[]=payout_type&fields[]=conversion_cap&fields[]=preview_url&fields[]=payout_cap&fields[]=name&fields[]=id&fields[]=description&fields[]=default_payout&filters[payout_type]=cpa_flat';
        $url = 'https://api.hasoffers.com/Apiv3/json?NetworkId=wmadv&Target=Affiliate_Offer&Method=findMyApprovedOffers&api_key='.$this->app_key.'&limit='.$limit.'&contain[]=TrackingLink&contain[]=Country'.$filters;

        set_time_limit(0);
        echo '开始:'.date("H:i:s")."<br />";
        $get_str = file_get_contents($url);
        $get_content = json_decode($get_str,true);//dump($get_content['response']['data']['data']);exit;
        echo '获取数据：'.date("H:i:s")."<br />";

        $i = $j = $m = 0;
        $new_offerids = $update_offerids = '';
        $all_offerids = $update_data = $insert_data = array();

        if($get_content['response']['status'] == 1){
            $data_arr = $get_content['response']['data']['data'];
            if(!empty($data_arr)){
                //轮询所有数据
                foreach($data_arr as $k=>$v){
                    $tmp = array();

                    $tmp['id'] = $v['Offer']['id'];
                    $tmp['name'] = $v['Offer']['name'];
                    $tmp['description'] = $v['Offer']['description'];
                    $tmp['preview_url'] = $v['Offer']['preview_url'];
                    $tmp['click_url'] = $v['TrackingLink']['click_url'];
                    $tmp['default_payout'] = number_format($v['Offer']['default_payout'],2);
                    if(strpos($v['Offer']['preview_url'], 'play.google.com') !== false)
                    {
                        $tmp['os'] = 'android';
                    } elseif(strpos($v['Offer']['preview_url'], 'itunes.apple.com') !== false) {
                        $tmp['os'] = 'ios';
                    } else {
                        continue;
                    }
                    if(!empty($v['Country'])) {
                        $countrys = array_keys($v['Country']);
                        $tmp['country'] = implode(',',$countrys);
                    } else {
                        $tmp['country'] = '';
                    }

                    $tmp['conversion_cap'] = $v['Offer']['conversion_cap'];

                    $all_offerids[] = $v['Offer']['id'];


                    $offer_info = $data_mod->find($tmp['id']);
                    if(!empty($offer_info)){ //该offer已经存在,对比信息是否有更新
                        $diff_arr = array();
                        $offer_info = $offer_info->toArray();

                        if($offer_info['default_payout'] != $tmp['default_payout']){ //如果价格有更新，则获取更新数据
                            $diff_arr['update_time'] = time();
                            $diff_arr['id'] = $tmp['id'];
                            $diff_arr['default_payout'] = $tmp['default_payout'];
                            $diff_arr['offer_status'] = 2;// 2表示等待更新
                            $update_data[] = $diff_arr;
                            $i++;//更新数
                            $update_offerids .= $tmp['id'].',';//记录日志用的
                        } else {
                            $j++;//已有数
                        }


                    } else { //该offer不存在,获取新增数据
                        $time = time();
                        $tmp['update_time'] = $time;
                        $tmp['create_time'] = $time;
                        $insert_data[] = $tmp;

                        $new_offerids .=$tmp['id'].',';//记录日志用的

                        $m++;//新增数
                    }
                }
            }
        }

        echo '循环数据：'.date("H:i:s")."<br />";
        //新增记录

        if(!empty($insert_data))
        {
            $insert_res = $data_mod->saveAll($insert_data,false);
        }

        //更新记录
        if(!empty($update_data))
        {
            $update_res = $data_mod->isUpdate()->saveAll($update_data);
        }


        //将本次没有获取的单子全部做下线处理
        $data_mod->whereNotIn('id',$all_offerids)->where(array('offer_status'=>1))->update(array('update_time'=> time(),'offer_status'=> 3));
        //记录日志
        save_apilog('add_offersId:'.$new_offerids,'mobupps');
        save_apilog('update_offersId:'.$update_offerids,'mobupps');

        echo '插入数据：'.date("H:i:s")."<br />";

        echo '更新数据:'.$i."<br />";
        echo '已有数据:'.$j."<br />";
        echo '新增数据:'.$m."<br />";
    }


    /*
     * 推送offer
     */
    public function postOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 92;
        $data_mod = new MobuppsData;


        //$info = $data_mod->limit(1)->find()->toArray();
        $insert_data = $data_mod->where(array('offer_id'=>0,'offer_status'=>0))->select()->toArray();
        //dump($insert_data);exit;
        if(empty($insert_data))
        {
            echo 'No offers add';
            exit;
        }
        foreach($insert_data as $info){
            //0.2以下的单子不导入
            /*if($info['price'] < 0.2) {
                continue;
            }*/

            $tracklink_str = '&aff_sub={click_id}&source={aff_id}&ios_ifa={ios_idfa}&google_aid={google_aid}';
            $destination_url = $info['click_url'].$tracklink_str;

            $countries = explode(',',$info['country']);
            $os_version = 0;

            $param = array(
                'name' => $info['name'],
                'preview_url' => empty($info['preview_url']) ? '' : $info['preview_url'],
                //'destination_url' => 'http://ads.dofunapps.com/acs.php?sid=6362&adid=7792014',
                'destination_url' => $destination_url,
                'description' => $info['description'],
                'offer_id' => $info['id'],
                'price' => $info['default_payout'],
                'os' => $info['os'],
                'os_version' => $os_version,
                'country' => $countries,
                'day_cap' => $info['conversion_cap'],
                'status' => 1,
            );
            $res = $offer_obj->addOffer($param,$advertiser_id);
            //dump($res);
            if($res['code'] != 0){
                save_apilog('post_fail:'.json_encode($res),'mobupps');
                continue;
            }
            //dump($param);dump($res);exit;
            //dump($res);
            $update_data = array('offer_id'=> $res['data']['offer']['id'],'offer_status'=> 1);
            //$data_mod->save($update_data,array('id'=> $info['id']));
            $data_mod->where(array('id'=> $info['id']))->update($update_data);
        }
        //dump($info);



    }

    /*
     * 更新offer
     */
    public function updateOffer()
    {
        $offer_obj = new Offer();
        $data_mod = new MobuppsData;
        $update_data = array();

        $update_offerid_list = $data_mod->where(array('offer_id'=>array('>',0),'offer_status'=>2))->field('id,default_payout,offer_id')->select()->toArray();//dump($update_offerid_list);exit;

        if(empty($update_offerid_list))
        {
            echo 'No offers update';
            exit;
        }
        foreach($update_offerid_list as $info){

            $offer_res = $offer_obj->updateOfferPrice($info['offer_id'],$info['default_payout']);
            if($offer_res['code'] != 0)
            {
                save_apilog('update_offer_price:'.json_encode($offer_res),'mobupps');
            }
            //dump($res);
            $update_data[] = array('id'=> $info['id'],'offer_status'=> 1);
        }
        //dump($info);


        $res = $data_mod->isUpdate()->saveAll($update_data);

    }

    /*
     * 更新offer状态
     */
    public function updateOfferStatus()
    {
        //$ids = array(127);
        $offer_obj = new Offer();

        $data_mod = new MobuppsData;
        //将单子下线
        $where = array(
            'offer_status'=> 3,
        );
        $list = $data_mod->field('offer_id')->where($where)->limit(100)->select()->toArray();
        $ids = array();
        foreach($list as $id){
            $ids[] = $id['offer_id'];
        }
        if(!empty($ids)){
            $res = $offer_obj->pausedOffer($ids);
            if($res['code'] != 0){
                save_apilog('paused_offer:'.json_encode($res),'mobupps');
            }
            $data_mod->whereIn('offer_id',$ids)->update(array('offer_status'=> -1));
        }


    }
}